<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\jzshop\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\jzshop\model\Brand as BrandModel;
 use app\jzshop\model\Supplier;
use Fastposter\Client;
use app\admin\model\Attachment as AttachmentModel;
use app\jzshop\job\Brand as JobBrand;
use app\jzshop\logic\Brand as LogicBrand;
use think\Db;
use think\Queue;

/**
 * 品牌控制器
 * @package app\jzshop\admin
 */
class Brand extends Admin
{
    /**
     * 品牌列表
     * @author 蔡伟明 <314013107@qq.com>
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function index()
    {
        // 查询
        $map = $this->getMap();
        // 排序
        $order = $this->getOrder('update_time desc');
        // 数据列表
        $data_list = BrandModel::where($map)->order($order)->paginate();

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setSearch(['name' => '标题']) // 设置搜索框
            ->addColumns([ // 批量添加数据列
                ['id', 'ID'],
                ['name', '品牌名称', 'text.edit'],
                ['logo', '品牌logo', 'picture'],
                ['design_code', '设计ID', 'text.edit'],
                ['create_time', '创建时间', 'datetime'],
                ['update_time', '更新时间', 'datetime'],
                ['right_button', '操作', 'btn']
            ])

            ->addTopButton('push', [
                'title' => '设计器',
                'icon'  => 'fa fa-fw fa-magic',
                'field' => 'id',
                'target-form' => 'ids',
                'class' => 'btn btn-success ajax-post confirm',
                'href'  => module_config('jzshop.fastposter_url')
            ])
            ->addTopButtons('add,delete') // 批量添加顶部按钮
            ->addRightButtons(['edit', 'delete' => ['data-tips' => '删除后无法恢复。']]) // 批量添加右侧按钮
            ->addOrder('id,name,create_time,update_time')
            ->setRowList($data_list) // 设置表格数据
            ->addValidate('Brand', 'name,url')
            ->fetch(); // 渲染模板
    }

    /**
     * 新增
     * @author 蔡伟明 <314013107@qq.com>
     * @return mixed
     * @throws \think\Exception
     */
    public function add()
    {
        // 保存数据
        if ($this->request->isPost()) {
            // 表单数据
            $data = $this->request->post();

            // 验证
            $result = $this->validate($data, 'Brand');
            if (true !== $result) $this->error($result);

            if ($Brand = BrandModel::create($data)) {

                $this->success('新增成功', 'index');
            } else {
                $this->error('新增失败');
            }
        }

        // 显示添加页面
        return ZBuilder::make('form')
            ->addFormItems([
                ['text', 'name', '品牌名称'],
                ['image', 'logo', '品牌LOGO'],
                ['text', 'design_code', '设计ID'],
            ])
            ->fetch();
    }

    /**
     * 编辑
     * @param null $id 品牌id
     * @author 蔡伟明 <314013107@qq.com>
     * @return mixed
     * @throws \think\Exception
     */
    public function edit($id = null)
    {
        if ($id === null) $this->error('缺少参数');

        // 保存数据
        if ($this->request->isPost()) {
            // 表单数据
            $data = $this->request->post();

            // 验证
            $result = $this->validate($data, 'Brand');
            if (true !== $result) $this->error($result);

            if (BrandModel::update($data)) {
                // 记录行为

                $this->success('编辑成功', 'index');
            } else {
                $this->error('编辑失败');
            }
        }

        $info = BrandModel::get($id);

        // 显示编辑页面
        return ZBuilder::make('form')
            ->addFormItems([
                ['hidden', 'id'],
                ['text', 'name', '品牌名称'],
                ['image', 'logo', '品牌LOGO'],
                ['text', 'design_code', '设计ID'],
            ])
            ->setFormData($info)
            ->fetch();
    }


    public function conflate($goods_id = null)
    {
        if ($goods_id === null) $this->error('缺少参数');

        $goods = Supplier::where(['id' => $goods_id])->find();

        if ($goods) {

            $Brand = BrandModel::where(['id' => $goods['brand_id']])->find();
            if (!$Brand) {
                $this->error('logo不存在，请上传logo后再试！');
            }
            $logo_path = get_file_path($Brand['logo']);
            if (!($goods['goods_main_image_temp'] > 0)) {
                $this->error('主图不存在，请上传后再试！');
            }


            $goods_main_image = get_file_path($goods['goods_main_image_temp']);

            $params = [
                "logo" =>  'http://host.docker.internal' . $logo_path,
                "goods" =>  'http://host.docker.internal' . $goods_main_image,
            ];

            if ($Brand['design_code'] == null) {

                $default_design_code =   module_config('jzshop.default_design_code');

                if (!$default_design_code) {
                    $this->error('默认设计ID未设置');
                } else {
                    $Brand['design_code'] = $default_design_code;
                }
            }
            $sqlite_param = [
                "logo" =>  'http://erp.lhp' . $logo_path,
                "goods" =>  'http://erp.lhp' . $goods_main_image,
                'code' => $Brand['design_code'],
                'title' => $goods['goods_title_alias'] . ' ' . $goods['goods_color_alias'],
                // 'height_price' => '某东价：' . $goods['sell_market_price'] . '元',
                // 'buy_price' =>  '虹创秒杀价：' . $goods['sell_daily_price'] . '元',
            ];


            if ($goods['sell_daily_price'] > 0) {
                $sqlite_param['buy_price'] = '虹创秒杀价：' . $goods['sell_daily_price'] . '元';
            } else {
                $sqlite_param['buy_price'] = '';
            }

            if ($goods['sell_market_price']) {

                if ($sqlite_param['buy_price']) {
                    $sqlite_param['height_price'] = '某东价：' . $goods['sell_market_price'] . '元';
                } else {
                    $sqlite_param['height_price'] = '虹创秒杀价：' . $goods['sell_market_price'] . '元';
                }
            } else {
                $sqlite_param['height_price'] = '';
            }

            $this->get_db_sqlite($sqlite_param,);

            $save = env('root_path') . 'public' . DIRECTORY_SEPARATOR . 'goods.png';
            # 1.创建海报客户端对象
            $client = new Client("fastposter-token", "http://127.0.0.1:5001");
            # 3.生成海报并保存(提供图片流、二进制、base64等多种方式)
            $filename = $client->buildPoster($Brand['design_code'], $params)->save($save);

            // echo '<img src="' . DIRECTORY_SEPARATOR . 'goods.png" />';die;
            $res = $this->saveImage($filename);

            if ($res) {
                Supplier::where(['id' => $goods_id])->update(['goods_main_image' => $res['id']]);
                $this->success('上传成功');
            } else {

                $this->error('上传失败');
            }
        } else {
            $this->error('商品不存在');
        }
    }

    public function conflates($id = null)
    {

        $ids = $this->request->param('ids', false);
        $id = $this->request->param('id', false);

        if ($id || $ids) {

            if ($id) {
                $ids = [$id];
            }
        } else {
            $this->error('参数错误');
        }
        if (count($ids) > 1) {
            foreach ($ids as $id) {
                $res[] = Queue::push(JobBrand::class, $id);
            }
            $this->success('提交成功', null, $res);
        } else {
            $res = LogicBrand::getInstance()->conflates($ids[0]);
            if ($res['status'] == 1) {
                $this->success($res['massage']);
            } else {
                $this->error($res['massage']);
            }
        }
    }
    private function saveImage($imagePath)
    {
        $dir_name = date('Ymd');
        $file_dir = config('upload_path') . DIRECTORY_SEPARATOR . 'images/' . $dir_name . '/';
        if (!is_dir($file_dir)) {
            mkdir($file_dir, 0766, true);
        }
        pathinfo($imagePath, PATHINFO_FILENAME);
        $new_file = $file_dir . DIRECTORY_SEPARATOR . md5_file($imagePath) . '.' . pathinfo($imagePath, PATHINFO_EXTENSION);
        rename($imagePath, $new_file);
        // 获取附件信息
        $file_info = [
            'uid' => session('user_auth.uid'),
            'name' => pathinfo($new_file, PATHINFO_FILENAME),
            'mime' => mime_content_type($new_file),
            'path' =>  str_replace('\\', '/', str_replace(env('root_path') . 'public\\', '', $new_file)),
            'ext' => pathinfo($new_file, PATHINFO_EXTENSION),
            'size' => filesize($new_file),
            'md5' => md5_file($new_file),
            'sha1' => sha1_file($new_file),
            'thumb' => '',
            'module' => 'jzshop',
            'width' => getimagesize($new_file)[0],
            'height' => getimagesize($new_file)[1],
        ];

        return AttachmentModel::create($file_info);
    }


    private function get_db_sqlite($data = [], $Sqlite_file = '')
    {
        if ($Sqlite_file == '') {
            $Sqlite_file = module_config('jzshop.fastposter_sqlite_path');
            if (!$Sqlite_file) {
                $this->error('fastposter设计器数据库地址未设置');
            }
        }
        $config = [
            // 数据库类型
            'type' => 'sqlite',
            // 数据库连接DSN配置
            'dsn' => 'sqlite:' . $Sqlite_file,
            // 数据库编码默认采用utf8
            'charset' => 'utf8',
        ];


        $Sqlite =   Db::connect($config)->table("posters")->where(['code' => $data['code']])->value('json');
        if (!$Sqlite) {
            $this->error('设计ID不存在');
        }
        $SqliteDatas = json_decode($Sqlite, true);;
        foreach ($SqliteDatas['items'] as   &$value) {
            if (isset($data[$value['vd']])) {

                $value['v'] = $data[$value['vd']];
            }
        }

        Db::connect($config)->table("posters")->where(['code' => $data['code']])->update(['json' => json_encode($SqliteDatas, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)]);
        return json_decode($Sqlite, true);
    }
}
